#研究报告相关
config = require('../config')
Schema = config.Schema
modeldb = config.modeldb
gridfs = new (require('../services/gridfs').FileStoreService)(config.fsdb.db)
ObjectId = require('mongoose').Types.ObjectId
resErr = require('./util').resErr
fsdb = require('../config').fsdb.db

exports.file_upload = (req,res) ->
  gridfs_id = new ObjectId()
  file = req.files.attach_file
  if !file 
    for _file of req.files
      file = req.files[_file]
      break
  file.name = req.param('filename') if req.param('filename')
  console.log file.size
  if req.param("_max_file_size") &&  parseInt(req.param("_max_file_size")) < file.size
    resErr res,"文件大小不得超过" + (parseInt(req.param("_max_file_size")) /1000) + "k"
  console.log file.name
  console.log file.type
  gridfs.uploadFile gridfs_id,file, (err) ->
    if err
      resErr(res,err)
    else
      result = {}
      result.success = true
      result.file_id = gridfs_id
      result.file_name = file.name
      result.file_size = file.size
      res.json result

#如果该文件名已经存在  那么删除
exports.file_upload_delete = (req,res) ->
  req.files.attach_file.name = req.param('filename') if req.param('filename')
  gridfs_id = new ObjectId()
  _filename = req.param('filename') || '____tmpfilename____'
  #如果传入的_attach_file_name，那么控件名称位_attach_file_name对应
  #默认取attach_file控件对应的文件
  attach_file = req.param('attach_file_name') || 'attach_file'
  fsdb.collection 'fs.files',(err,coll)->
    if err
      return cb err
    gridfs.deleteFileByName _filename,(err)->
      return cb err if err
      gridfs.uploadFile gridfs_id,req.files['attach_file'], (err) ->
        if err
          resErr(res,err)
        else
          result = {}
          result.success = true
          result.file_id = gridfs_id
          result.file_name = req.files.attach_file.name
          res.json result


exports.file_uploadck = (req,res) ->
  gridfs_id = new ObjectId()
  gridfs.uploadFile gridfs_id,req.files.upload, (err) ->
    if err
      callback = req.param("CKEditorFuncNum")
      result = "<script type=\"text/javascript\">"
      err_msg = "'系统发生异常');"
      result += "window.parent.CKEDITOR.tools.callFunction(" + callback + ",''," + err_msg
      result += "</script>"
      res.send result
    else
      callback = req.param("CKEditorFuncNum")
      result = "<script type=\"text/javascript\">"
      result += "window.parent.CKEDITOR.tools.callFunction("+ callback + ",'" +"/file/download?file_id="+ gridfs_id + "','')"
      result += "</script>"
      res.send result


#文件下载
exports.file_download = (req,res) ->
  _src = ''
  if req.param('filename')
    _src = req.param('filename')
    if _src && (_src.length == 12 || _src.length == 24)
      if /^[0-9a-fA-F]+$/.test(_src)
        _src = new ObjectId(_src)
  else
    file_id = req.param('file_id')

    if file_id && (file_id.length == 12 || file_id.length == 24)
      if /^[0-9a-fA-F]+$/.test(file_id)
        _src = new ObjectId(req.param('file_id'))

  if !_src
    resErr res,'文件id不合法'
  gridfs.readFile _src, (err,contentType,filename, gs) ->
    console.log file_id+'文件类型:'+contentType
    if err
      return resErr(res,err)
    if contentType && contentType.match(/^image\//)
      res.header("Content-Type",contentType)
    else if contentType && contentType == 'application/x-shockwave-flash'
      res.header("Content-Type",contentType)
    else
      res.header("Content-Type",contentType)
      ua=req.headers['user-agent']
      if ua.match /Firefox/i
        fname=new Buffer(filename,'utf-8')
        res.header('Content-Disposition', 'attachment; filename='+fname)
      else
        res.header('Content-Disposition', 'attachment; filename='+encodeURIComponent(filename))
    #res.set('Content-Disposition', 'attachment; filename='+filename)

    try
      gs.stream(false).pipe(res)
    catch ex
      return resErr(res,ex)
    finally
      gs.close()

exports.file_upload_2 = (req,res) ->
  console.log 'file_upload_2....'
  gridfs_id = new ObjectId()
  file = req.files.attach_file_2
  if !file 
    for _file of req.files
      file = req.files[_file]
      break
  file.name = req.param('filename') if req.param('filename')
  console.log file.size
  if req.param("_max_file_size") &&  parseInt(req.param("_max_file_size")) < file.size
    resErr res,"文件大小不得超过" + (parseInt(req.param("_max_file_size")) /1000) + "k"
  console.log file.name
  console.log file.type
  gridfs.uploadFile gridfs_id,file, (err) ->
    if err
      resErr(res,err)
    else
      result = {}
      result.success = true
      result.file_id = gridfs_id
      result.file_name = file.name
      result.file_size = file.size
      res.json result

#通用上传方式，支持一个表单中的多个文件上传
#filefield_name参数必传
exports.file_common_upload = (req,res) ->
  #console.log 'file_common_upload...'
  gridfs_id = new ObjectId()
  filefield_name = req.param('filefield_name')
  return resErr res, '表单filefield组件的name值（参数名filefield_name）不能为空！' if !filefield_name
  #console.log filefield_name
  #file = req.files.attach_file
  file = req.files[filefield_name]
  if !file 
    for _file of req.files
      file = req.files[_file]
      break
  file.name = req.param('filename') if req.param('filename')
  console.log file.size
  if req.param("_max_file_size") &&  parseInt(req.param("_max_file_size")) < file.size
    resErr res,"文件大小不得超过" + (parseInt(req.param("_max_file_size")) /1000) + "k"
  console.log file.name
  console.log file.type
  gridfs.uploadFile gridfs_id,file, (err) ->
    if err
      resErr(res,err)
    else
      result = {}
      result.success = true
      result.file_id = gridfs_id
      result.file_name = file.name
      result.file_size = file.size
      res.json result